package com.sky.controller.user;

import com.sky.constant.CacheKeyRuleConstant;
import com.sky.constant.StatusConstant;
import com.sky.entity.Dish;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Set;

@Slf4j
@RestController("userDishController")
@RequestMapping("/user/dish")
@Api(tags = "C端-菜品接口")
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 根据分类 id 查询菜品
     * 添加缓存机制
     * @return
     */
    @ApiOperation("根据分类 id 查询菜品")
    @GetMapping("/list")
    public Result<List<DishVO>> listByCategory(Long categoryId) {
        // 构造 redis 中的 key，规则：dish_categoryId
        String key = CacheKeyRuleConstant.DISH_KEY + categoryId;
        // 查询 redis 中的是否存在菜品数据
        List<DishVO> dishVOList = (List<DishVO>) redisTemplate.opsForValue().get(key);
        if(CollectionUtils.isNotEmpty(dishVOList)) {
            // 存在，不查询 mysql 直接返回
            return Result.success(dishVOList);
        }
        // 不存在
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)      //查询启售中的菜品
                .build();
        dishVOList = dishService.listWithFlavor(dish);
        //将查询到的数据放入缓存中
        redisTemplate.opsForValue().set(key, dishVOList);
        return Result.success(dishVOList);
    }

}
